package com.joint.cloud.common.exception;

import com.joint.cloud.common.constants.ResponseCode;
import com.joint.cloud.common.constants.ResponseResult;
import com.joint.cloud.common.response.BaseResponse;
import com.joint.cloud.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice(annotations = BaseResponse.class)
@ResponseBody
public class ExceptionHandlerAdvice {

    private static final Logger log = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
    /**
     * 处理未捕获的Exception
     *
     * @param e 异常
     * @return 统一响应体
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseResult(ResponseCode.SERVICE_ERROR.getCode(), ResponseCode.SERVICE_ERROR.getMsg(), null, StringUtils.getStackMessage(e));
    }

    /**
     * 处理未捕获的RuntimeException
     *
     * @param e 运行时异常
     * @return 统一响应体
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult handleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return new ResponseResult(ResponseCode.SERVICE_ERROR.getCode(), ResponseCode.SERVICE_ERROR.getMsg(), null, StringUtils.getStackMessage(e));
    }

    /**
     * 处理业务异常BaseException
     *
     * @param e 业务异常
     * @return 统一响应体
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseResult handleBaseException(BusinessException e) {
        ResponseCode code = e.getCode();
        if (e.getMsg() != null) {
            return new ResponseResult(code.getCode(), e.getMsg(), null, null);
        }
        return new ResponseResult(code.getCode(), code.getMsg(), null, null);
    }

    /**
     * 处理业务异常BaseException
     *
     * @param e 业务异常
     * @return 统一响应体
     */
    @ExceptionHandler(AIOpsException.class)
    public ResponseResult handleBaseException(AIOpsException e) {
        log.error(e.getMessage(), e);
        ResponseCode code = e.getCode();
        if (e.getErrorMsgLocal() != null) {
            return new ResponseResult(code.getCode(), e.getErrorMsgLocal(), null, null);
        }
        return new ResponseResult(code.getCode(), code.getMsg(), null, null);
    }

    /**
     * 参数校验异常MethodArgumentNotValidException
     *
     * @param e 业务异常
     * @return 统一响应体
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleBindException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        String message = "";
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                log.error("Data check failure : object{" + fieldError.getObjectName() + "},field{" + fieldError.getField() +
                        "},errorMessage{" + fieldError.getDefaultMessage() + "}");

            });
            if (errors.size() > 0) {
                FieldError fieldError = (FieldError) errors.get(0);
                message = fieldError.getDefaultMessage();
            }
        }
        return new ResponseResult(ResponseCode.BAD_REQUEST.getCode(), message, null, null);
    }
}
